package org.wx.zk.comm;


import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * @description: zk 帮助类
 * @author: wangxun
 * @createDate: 2021/3/23
 * @version: 1.0
 */
@Slf4j
public class ZKUtils {
    static ZooKeeper zk;
    static ZKConf zkConf;
    static DefaultWatcher defaultWatcher = new DefaultWatcher();

    /**
     * 获取客户端
     * @return
     */
    public static ZooKeeper getZK(){
        try {
            log.info("获取zk client ....");
            // 设置门栓 当正常连接的时候才向下执行
            final CountDownLatch cd = new CountDownLatch(1);
            defaultWatcher.setCd(cd);
            zk = new ZooKeeper(ZKConf.ADDRESS, zkConf.SESSIONTIMEOUT, defaultWatcher);
            try {
                // 阻塞住线程
                cd.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return zk;
    }

    /**
     * 关闭客户端
     */
    public static void closeZK(){
        try {
            zk.close();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
